import { login, getUserInfo } from '@/api/user'
import { setToken, getToken, removeToken } from '@/utils/auth'
export default {
  namespaced: true,
  state: {
    token: getToken(),
    userInfo: {},
    userId: '',
    hrsaasTime: ''
  },
  mutations: {
    // 保存时间节点
    sethrsaasTime(state, time) {
      state.hrsaasTime = time
    },
    setToken(state, token) {
      state.token = token
      setToken(token)
    },
    removeToken(state) {
      state.token = null
      removeToken()
    },
    // 设置用户信息
    setUserInfo(state, userInfo) {
      state.userInfo = JSON.parse(JSON.stringify(userInfo))
    },
    // 删除用户信息
    removeUserInfo(state) {
      state.userInfo = {}
    },
    setUserId(state, payload) {
      state.userId = payload
    }
  },
  actions: {
    async login({ commit }, data) {
      const res = await login(data)
      console.log(res)
      commit('sethrsaasTime', +new Date())
      commit('setToken', res.token)
      commit('setUserId', res.userId)
    },
    async getUserInfo({ commit, state }) {
      const res = await getUserInfo(state.userId)
      console.log(res)
      commit('setUserInfo', res)
    },
    logout({ commit }) {
      commit('removeToken')
      commit('removeUserInfo')
    }
  }
}
